layui.define(["upload", "element"], function (exports) {
  var $ = layui.$,
    upload = layui.upload,
    element = layui.element;

  var meetingDetailsData = layui.sessionData("meetingDetailsData").key;
  $(".meetingHeadline").text(meetingDetailsData.meetingName || "");
  $(".startTime").text(meetingDetailsData.startTime);
  $(".endTime").text(meetingDetailsData.endTime);
  $(".projectName").text(meetingDetailsData.projectName);
  $(".meetingOriginator").text(meetingDetailsData.meetingOriginator);
  $(".meetingOriginatorUnit").text(meetingDetailsData.meetingUnits);
  $(".site").text(meetingDetailsData.roomId);
  $(".remarks").text(meetingDetailsData.remarks);
  $(".meetingAttendanceContent").html(meetingDetailsData.ackMsg);
  $(".meetingSign").on("click", function () {
    $.ajax({
      url: base_url + "/meeting/download/4/" + meetingDetailsData.meetingId,
      async: true,
      type: "GET",
      headers: {
        Accept: "application/json; charset=utf-8",
        Authorization: layui.sessionData("userToken").key,
      },
      success: function (data) {
        if (data.code == "200") {
          window.location.href =
            base_url + "/meeting/download/4/" + meetingDetailsData.meetingId;
        } else {
          layer.msg(data.message, { icon: 5 });
        }
      },
    });
  });
  $(".downLoadSummary").on("click", function () {
    window.location.href =
      "mfu://roomId=" +
      meetingDetailsData.meetingId +
      "&userNumber=" +
      layui.sessionData("userName").key;
  });
  $.ajax({
    type: "get",
    async: true, //异步执行
    url: base_url + "/meeting/voices/" + "123456",
    headers: {
      Accept: "application/json; charset=utf-8",
      Authorization: layui.sessionData("userToken").key,
    },
    contentType: "application/json",
    success: function (data) {
      if (data.code == 200) {
        if (data.hasOwnProperty("data")) {
          var dataList = data.data;
          dataList.forEach((item, index) => {
            var htmlVido = `<div class="waveform" id="waveform${index}" style="width: 100%; height: 100px"></div>
              <audio class="audio"
              id="audio${index}"
              src="video.mp4"
              controls="" width="100%"
            ><a></a></audio><div class="meetingOpearBtn" data-id="${item.id}">
              <div class="meetingSummaryEdit"><i class="layui-icon layui-icon-edit"></i>保存</div>
            <div class="meetingSummaryDown"><i class="layui-icon layui-icon-download-circle"></i>下载</div>
            </div> <div class="turnText"> <textarea class="turnTextCon turnTextCon${index}">${item.text}</textarea></div>`;
            element.tabAdd("meetingMinutesTable", {
              title: "音频" + (index + 1), //用于演示
              content: htmlVido,
              id: index + 1,
            });
            element.tabChange("meetingMinutesTable", 1);
            element.on("tab(meetingMinutesTable)", function (data) {
              wavesurferFun(data.index);
            });
          });
        }
        $(".meetingSummaryEdit").on("click", function () {
          var id = $(this).parent().attr("data-id");
          var summaryData = $(this)
            .parent()
            .siblings()
            .children("textarea")
            .val();
          $.ajax({
            url: base_url + "/meeting/update/meetingSummary",
            async: true,
            type: "post",
            data: {
              id: id,
              data: summaryData,
            },
            headers: {
              Accept: "application/json; charset=utf-8",
              Authorization: layui.sessionData("userToken").key,
            },
            success: function (data) {
              if (data.code == "200") {
                layer.msg(data.message, { icon: 1 });
              }
            },
          });
        });
        // 会议纪要下载
        $(".meetingSummaryDown").on("click", function () {
          var id = $(this).parent().attr("data-id");
          window.location.href = base_url + "/meeting/download/" + id;
        });
      }
    },
  });
  function wavesurferFun(index) {
    if (
      document.getElementById(`waveform${index}`).getElementsByTagName("wave")
        .length > 0
    ) {
      return;
    }
    var audio = document.getElementById(`audio${index}`);
    var wavesurfer = WaveSurfer.create({
      container: "#waveform" + index, //#waveform1  #waveform2
      hideScrollbar: true, // 横坐标显示
      barWidth: true, // 波形展示为柱状
      height: 100,
      padding: 5,
      backgroundColor: "#EEF3EF",
      waveScale: 0.8,
      mediaType: "audio",
    });
    wavesurfer.load(audio.getAttribute("src"));
    var audios = document.getElementsByTagName("audio");
    // 暂停函数
    function pauseAll() {
      var self = this;
      [].forEach.call(audios, function (i) {
        // 将audios中其他的audio全部暂停
        i !== self && i.pause();
      });
    }
    // 给play事件绑定暂停函数
    [].forEach.call(audios, function (i) {
      i.addEventListener("play", pauseAll.bind(i));
    });

    audio.addEventListener("playing", function () {
      wavesurfer.play();
    });
    audio.addEventListener("pause", function () {
      wavesurfer.pause();
    });
    audio.addEventListener("seeked", function () {});
    audio.addEventListener("muted", function () {});
  }
  $.ajax({
    type: "get",
    async: true, //异步执行
    url: base_url + "/meeting/files/" + meetingDetailsData.meetingId,
    headers: {
      Accept: "application/json; charset=utf-8",
      Authorization: layui.sessionData("userToken").key,
    },
    contentType: "application/json",
    success: function (data) {
      if (data.code == 200) {
        var str = "";
        data.data.forEach((item, index) => {
          str += ` <div class="layui-col-md6"><p>${item.fileName}</p><div class="suppleInformationBtn" data-id="${item.id}"><button class="deleteData layui-btn layui-btn-xs technicalReviewBtn layui-btn-danger">删除</button><button class="layui-btn layui-btn-xs technicalReviewBtn technicalRequirement downloadData">下载</button></div></div>`;
          $(".suppleInformation").html(str);
        });
      }
    },
  });
  $(".suppleInformation").on("click", ".downloadData", function () {
    var id = $(this).parent().attr("data-id");
    window.location.href = base_url + "/meeting/download/" + id;
  });
  $(".suppleInformation").on("click", ".deleteData", function () {
    var id = $(this).parent().attr("data-id");
    var removeElement = $(this).parent().parent();
    $.ajax({
      type: "get",
      async: true, //异步执行
      url: base_url + "/meeting/file/delete/" + id,
      headers: {
        Accept: "application/json; charset=utf-8",
        Authorization: layui.sessionData("userToken").key,
      },
      contentType: "application/json",
      success: function (data) {
        if ((data.type = "success")) {
          layer.confirm("确认删除吗?", function (index) {
            removeElement.remove();
            layer.close(index);
            layer.msg(data.message, { icon: 6 });
          });
        } else {
          layer.msg(data.message, { icon: 5 });
        }
      },
    });
  });

  var uploader = new Uploader({
    target: base_url + "/meeting/upload/chunk",
    query: { meetingId: meetingDetailsData.meetingId },
    chunkSize: 1027 * 1024,
    testMethod: "GET",
    headers: {
      Accept: "application/json; charset=utf-8",
      Authorization: layui.sessionData("userToken").key,
    },
  });
  // 如果不支持 需要降级的地方
  if (!uploader.support) location.href = "/some-old-crappy-uploader";

  uploader.assignBrowse(document.getElementsByClassName("uploadAudio"));

  uploader.on("fileAdded", function (file, event) {
    computeMD5(file);
  });
  uploader.on("fileSuccess", function (rootFile, file, message) {
    mergerChunk(file);
  });
  function mergerChunk(file) {
    $.ajax({
      url: base_url + "/meeting/upload/chunk/merge",
      headers: {
        Accept: "application/json; charset=utf-8",
        Authorization: layui.sessionData("userToken").key,
      },
      contentType: "application/json",
      async: true,
      dataType: "json",
      type: "post",
      data: JSON.stringify({
        filename: file.name,
        identifier: file.uniqueIdentifier,
        totalSize: file.size,
        totalChunks: file.chunks.length,
        meetingId: meetingDetailsData.meetingId,
      }),
      success: function (res) {
        console.log("merger success");
      },
    });
  }
  function computeMD5(file) {
    let blobSlice =
        File.prototype.slice ||
        File.prototype.mozSlice ||
        File.prototype.webkitSlice,
      chunkSize = 2097152,
      chunks = Math.ceil(file.size / chunkSize),
      currentChunk = 0,
      spark = new SparkMD5.ArrayBuffer(),
      fileReader = new FileReader();
    let time = new Date().getTime();
    // console.log('计算MD5...')
    file.cmd5 = true;

    fileReader.onload = (e) => {
      spark.append(e.target.result); // Append array buffer
      currentChunk++;

      if (currentChunk < chunks) {
        console.log(
          `第${currentChunk}分片解析完成, 开始第${
            currentChunk + 1
          } / ${chunks}分片解析`
        );
        // let percent = Math.floor(currentChunk / chunks * 100);
        // console.log(percent);
        // file.cmd5progress = percent;
        loadNext();
      } else {
        console.log("finished loading");
        let md5 = spark.end();
        console.log(
          `MD5计算完成：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${
            file.size
          } 用时：${new Date().getTime() - time} ms`
        );
        spark.destroy(); //释放缓存
        file.uniqueIdentifier = md5; //将文件md5赋值给文件唯一标识
        file.cmd5 = false; //取消计算md5状态
        file.resume(); //开始上传
        console.log(file);
      }
    };
    fileReader.onerror = () => {
      console.warn("oops, something went wrong.");
      file.cancel();
    };

    let loadNext = () => {
      let start = currentChunk * chunkSize,
        end = start + chunkSize >= file.size ? file.size : start + chunkSize;

      fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
    };

    loadNext();
  }

  function processResponse(response, cb) {
    console.log("ddddd");
  }

  //演示多文件列表
  var uploadListIns = upload.render({
    elem: ".uploadSummary",
    elemList: $("#demoList"), //列表元素对象
    url: base_url + "/meeting/upload/" + meetingDetailsData.meetingId,
    accept: "file",
    multiple: true,
    type: "get",
    headers: {
      Accept: "application/json; charset=utf-8",
      Authorization: layui.sessionData("userToken").key,
    },
  });

  exports("meetingsManagementDetails", {});
});
